﻿using System.ComponentModel;
using System.Reflection;

namespace Dyao.Book.Core
{
    public class EnumDescriptionValueFormatter : IAdditionDataValueFormatter
    {
        public object Format(object value)
        {
            var desc = string.Empty;
            if (value == null) return desc;

            var enumValue = value as Enum;

            if (enumValue == null) return value.ToString();

            FieldInfo fi = enumValue.GetType().GetField(enumValue.ToString());

            if (fi == null) return value.ToString();

            var attr = fi.GetCustomAttribute<DescriptionAttribute>(false);
            if (attr != null)
            {
                desc = attr.Description;
            }

            if (string.IsNullOrWhiteSpace(desc))
            {
                desc = fi.Name;
            }

            return desc;
        }
    }
}
